import { _decorator, Component, Node, Prefab, instantiate } from "cc";
import { BaseComponent } from "../../core/component/BaseComponent";
import { getNumFloor } from "../../core/utils/utils";
import { dataManager } from "../data/DataManager";
import { EnemyData } from "../data/EnemyData";
import { BELONG_TYPE } from "../data/MapData";
import { PlayerData } from "../data/PlayerData";
import { MaterialItem } from "./MaterialItem";
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = ResourceBar
 * DateTime = Sat Dec 25 2021 15:06:48 GMT+0800 (中国标准时间)
 * Author = han2007happy
 * FileBasename = ResourceBar.ts
 * FileBasenameNoExtension = ResourceBar
 * URL = db://assets/scripts/game/component/ResourceBar.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/en/
 *
 */

@ccclass("ResourceBar")
export class ResourceBar extends BaseComponent {
    @property({ type: Prefab, displayName: "资源预制" })
    materialItemPrefab: Prefab | undefined;

    @property({ type: Number, displayName: "归属" })
    belong!: number;

    start() {
        // [3]
    }

    setData() {
        let metalIdx = 0;
        const dataPlayer: PlayerData | EnemyData = dataManager.dataMap.getPlayerByBelong(this.belong)!;
        const materials = dataPlayer.resourceList;
        const soldiers = dataPlayer.soldierList;

        for (const materialId in materials) {
            const materialQuantity = materials[materialId];
            this.setMaterialItem(materialId, materialQuantity, metalIdx);
            metalIdx++;
        }

        const dispatchingSoldiers = dataManager.dataPlayer.getDispatchArmySoldiers();
        for (const soldierId in soldiers) {
            const dispatchSoldierNum = dispatchingSoldiers[soldierId] ? dispatchingSoldiers[soldierId] : 0;
            const soldierQuantity = soldiers[soldierId] + dispatchSoldierNum;
            this.setMaterialItem(soldierId, soldierQuantity, metalIdx);
            metalIdx++;
        }
    }

    setMaterialItem(materialId: string, materialQuantity: number, metalIdx: number) {
        let materialItemNode = this.node.children[metalIdx];
        if (!materialItemNode) {
            if (this.materialItemPrefab) {
                materialItemNode = instantiate(this.materialItemPrefab);
            } else {
                materialItemNode = instantiate(this.node.children[0]);
            }
            materialItemNode.parent = this.node;
        }
        materialItemNode.getComponent(MaterialItem)!.setData(materialId, getNumFloor(materialQuantity));
    }
}
